package com.lmk.ms.common.net.udp.client;

import com.lmk.ms.common.net.udp.client.service.UdpClientService;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * UDP 客户端
 * @author laomake@hotmail.com
 * @version 1.0
 * @date 2023/4/25
 */
@Slf4j
public class UdpClient {

    /**
     * 服务端IP地址
     */
    private String serverHost;

    /**
     * 服务端监听端口
     */
    private int serverPort;

    /**
     * 服务端IP地址
     */
    private String localHost;

    /**
     * 服务端监听端口
     */
    private int localPort;

    /**
     * 客户端IP
     */
    private UdpClientService ss;

    public UdpClient(String serverHost, int serverPort, String localHost, int localPort, UdpClientService ss) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
        this.localHost = localHost;
        this.localPort = localPort;
        this.ss = ss;
    }

    public void run() {
        InetAddress localAddress = null;
        InetAddress serverAddress = null;
        try {
            localAddress = InetAddress.getByName(localHost);
            serverAddress = InetAddress.getByName(serverHost);
        } catch (UnknownHostException e) {
            log.error("网络地址解析失败：", e);
            return;
        }

        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(localPort, localAddress);
            ss.handel(socket, serverAddress, serverPort);
        } catch (IOException e) {
            log.error("客户端异常：", e);
        } finally {
            if(socket != null){
                log.debug("关闭客户端...");
                socket.close();
            }
        }
        log.debug("客户端退出");
    }
}
